import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:get/get.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:ball_lion/module/match/list/match_page_logic.dart';
import 'package:ball_lion/module/match/list/zq_focus_logic.dart';
import 'package:ball_lion/service/config_service.dart';
import 'package:ball_lion/service/umeng_service.dart';
import 'package:ball_lion/entity/match/zq_list_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/constant.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/match_zq_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class ZqMatchCell extends StatefulWidget {
  final ZqListEntity match;
  final MatchListProvider logic;
  const ZqMatchCell(this.match, this.logic, {super.key});

  @override
  State<ZqMatchCell> createState() => _ZqMatchCellState();
}

class _ZqMatchCellState extends State<ZqMatchCell> {
  ZqConfig config = Get.find<ConfigService>().zqConfig;
  double teamLogo = 18.0;
  // late String ticketName = Get.find<MatchPageLogic>()
  //     .getMatchController()
  //     .getTicketName(widget.match);

  @override
  Widget build(BuildContext context) {
    //加时显示
    String finalString = '';
    if (widget.match.neutrality == 1) {
      finalString = '中立场';
      if (widget.match.locationCn.hasValue) {
        finalString += '：${widget.match.locationCn}';
      }
    }
    if (widget.match.status == '7' && widget.match.homeScoreOt != null) {
      //优先显示加时信息
      finalString = '';
      finalString +=
          '90分钟[${widget.match.homeScore90}-${widget.match.guestScore90}]  120分钟[${widget.match.homeScoreOt}-${widget.match.guestScoreOt}]';
      if (widget.match.homeScorePk != null) {
        finalString +=
            '  点球[${widget.match.homeScorePk}-${widget.match.guestScorePk}]';
      }
      int homeScore =
          widget.match.homeScoreOt! + (widget.match.homeScorePk ?? 0);
      int guestScore =
          widget.match.guestScoreOt! + (widget.match.guestScorePk ?? 0);
      if (homeScore > guestScore) {
        finalString += '  ${widget.match.homeName}胜出';
      } else {
        finalString += '  ${widget.match.guestName}胜出';
      }
      // finalString +=
    }

    return GestureDetector(
      onTap: () {
        Utils.onEvent('match_view', params: {'match_id': widget.match.id});
        // Get.find<UmengService>().payOriginRoute = 'bspd';
        Get.toNamed(
          Routes.zqMatchDetail,
          arguments: widget.match.id,
          // parameters: {"roomId": widget.match.roomId.hasValue?"${widget.match.roomId}":''}
        );
      },
      child: Block(
        cardStyle: CardStyle(
            margin: EdgeInsets.only(
                bottom: widget.match.lastMatchInDay ? 0 : 8,
                left: 8,
                right: 8,
                top: widget.match.needTopSpace ? 8 : 0),
            shadow: const BoxShadow(color: Colours.transparent)),
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.fromLTRB(8, 8, 8, 7),
              child: Column(
                children: [
                  top(),
                  const SizedBox(height: 4),
                  body(),
                  events(),
                  bottom(),
                ],
              ),
            ),
            if (finalString.isNotEmpty) ...[
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 12),
                height: 0.5,
                color: Colours.greyEE,
              ),
              Container(
                height: 26,
                alignment: Alignment.center,
                width: double.infinity,
                child: QsText(
                  finalString,
                  maxLines: 1,
                  fontSize: 11,
                  color: Colours.main,
                ),
              )
            ]
          ],
        ),
      ),
    );
  }

  Widget top() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.max,
      children: [
        Flexible(
          fit: FlexFit.tight,
          flex: 2,
          child: Row(
            textBaseline: TextBaseline.alphabetic,
            crossAxisAlignment: CrossAxisAlignment.baseline,
            children: [
              QsText(
                widget.match.leagueName,
                color: widget.match.leagueColor == null
                    ? Colours.grey66
                    : HexColor(widget.match.leagueColor!),
                fontSize: 11,
                needCenter: true,
              ),
              if (widget.match.rounds != null) ...[
                const SizedBox(width: 4),
                QsText(
                  '第${widget.match.rounds}轮',
                  color: Colours.grey66,
                  fontSize: 11,
                  needCenter: true,
                ),
              ],
              const SizedBox(width: 4),
              QsText(
                widget.match.matchTime.noValue
                    ? null
                    : DateTimeUtils.formatDateString(
                        widget.match.matchTime!, 'HH:mm'),
                needCenter: true,
                color: Colours.grey66,
                fontSize: 11,
              ),
              const SizedBox(width: 4),
              if (config.zqList3 == 1)
                QsText(widget.logic.getTicketName(widget.match),
                    color: Colours.grey66, fontSize: 11)
            ],
          ),
        ),
        Flexible(
          flex: 1,
          child: Center(
              child: (widget.match.status == '2' || widget.match.status == '4')
                  ? Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        QsText(widget.match.show,
                            color: HexColor(widget.match.color!), fontSize: 11),
                        QsText('\'',
                                color: HexColor(widget.match.color!),
                                fontSize: 11)
                            .animate(
                              onPlay: (controller) => controller.repeat(),
                            )
                            .fade(duration: 1000.ms)
                      ],
                    )
                  : QsText(
                      widget.match.show == '未' ? '' : widget.match.show,
                      color: HexColor(widget.match.color!),
                      fontSize: 11,
                    )),
        ),
        Flexible(
            flex: 2,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                label(
                    show: widget.match.intelligence == 1,
                    name: Constant.baoliao,
                    color: Colours.main),
                label(
                    show: widget.match.lineup == 1,
                    name: Constant.zhenrong,
                    color: const Color(0xFF8A55FB)),
                label(
                    show: widget.match.planCnt != 0 && config.zqList4 == 1,
                    name: Constant.guandian,
                    extra:
                        "${widget.match.planCnt! > 99 ? "99+" : widget.match.planCnt}",
                    color: const Color(0xFF2469FD)),
                label(
                    show: widget.match.ai ?? false,
                    name: Constant.model,
                    color: const Color(0xFFF139BE)),
              ],
            ))
      ],
    );
  }

  Widget body() {
    return SizedBox(
      height: 36,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
              onTap: () async {
                if (User.isFollow(widget.match.id!)) {
                  Utils.onEvent('bspdzq', params: {'bspdzq': '7'});
                  await User.unFollow(widget.match.id!);
                } else {
                  Utils.onEvent('bspdzq', params: {'bspdzq': '9'});
                  await User.follow(widget.match.id!);
                }
                setState(() {});
                try {
                  Get.find<ZqFocusLogic>().getMatch();
                } catch (e) {}
                // matchInterestController.getMatch();
              },
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 4),
                // margin: EdgeInsets.only(left: 8),
                child: User.isFollow(widget.match.id!)
                    ? Image.asset(Utils.getImgPath("match_focus.png"),
                        color: Colours.main, width: 18)
                    : Image.asset(Utils.getImgPath("match_unfocus.png"),
                        color: Colors.grey, width: 18),
              )),
          Flexible(
              flex: 18,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  if (widget.match.homeYellow != null &&
                      widget.match.homeYellow != 0 &&
                      config.zqList5 == 1) ...[
                    card(0, true),
                    const SizedBox(width: 1)
                  ],
                  if (widget.match.homeRed != null &&
                      widget.match.homeRed != 0 &&
                      config.zqList5 == 1) ...[
                    card(1, true),
                    const SizedBox(width: 2)
                  ],
                  if (config.zqList2 == 1)
                    QsText(
                      (widget.match.homeRanking == null ||
                              widget.match.homeRanking == '')
                          ? ''
                          : '[${widget.match.homeRanking}]',
                      color: Colours.grey99,
                      fontSize: 11,
                    ),
                  const SizedBox(width: 1),
                  Flexible(
                    child: QsText(
                      widget.match.homeName ?? '',
                      maxLines: 2,
                      textAlign: TextAlign.right,
                      fontWeight: FontWeight.w500,
                      needCenter: true,
                      fontSize: 13,
                    ),
                  ),
                  const SizedBox(width: 3),
                  CachedNetworkImage(
                    imageUrl: widget.match.homeLogo ?? '',
                    placeholder: (context, url) => Styles.placeholderIcon(),
                    errorWidget: (context, url, error) => Image.asset(
                      Utils.getImgPath('zq_placeholder.png'),
                      height: teamLogo,
                      width: teamLogo,
                    ),
                    width: teamLogo,
                    height: teamLogo,
                    fit: BoxFit.contain,
                  )
                ],
              )),
          const SizedBox(width: 6),
          if (widget.match.homeScore90 != null &&
              widget.match.guestScore90 != null) ...[
            QsText(
              "${widget.match.homeScore90}-${widget.match.guestScore90}",
              fontSize: 16,
              fontFamily: "Din",
              color: Colours.main,
            )
          ] else ...[
            const QsText("vs",
                fontSize: 16, fontFamily: "Din", color: Colours.grey99)
          ],
          const SizedBox(width: 6),
          Flexible(
              flex: 20 -
                  (widget.match.video == 1
                      ? 3
                      : 0), //widget.match.onLive??false?5:
              child: Row(
                children: [
                  CachedNetworkImage(
                    imageUrl: widget.match.guestLogo ?? '',
                    placeholder: (context, url) => Styles.placeholderIcon(),
                    errorWidget: (context, url, error) => Image.asset(
                      Utils.getImgPath('zq_placeholder.png'),
                      height: teamLogo,
                      width: teamLogo,
                    ),
                    width: teamLogo,
                    height: teamLogo,
                    fit: BoxFit.contain,
                  ),
                  const SizedBox(width: 3),
                  Flexible(
                    child: QsText(
                      widget.match.guestName ?? '',
                      maxLines: 2,
                      fontWeight: FontWeight.w500,
                      needCenter: true,
                      fontSize: 13,
                    ),
                  ),
                  const SizedBox(width: 1),
                  if (config.zqList2 == 1)
                    QsText(
                        widget.match.guestRanking == null ||
                                widget.match.guestRanking == ''
                            ? ''
                            : '[${widget.match.guestRanking}]',
                        color: Colours.grey99,
                        fontSize: 11),
                  if (widget.match.guestRed != null &&
                      widget.match.guestRed != 0 &&
                      config.zqList5 == 1) ...[
                    const SizedBox(width: 2),
                    card(1, false),
                  ],
                  if (widget.match.guestYellow != null &&
                      widget.match.guestYellow != 0 &&
                      config.zqList5 == 1) ...[
                    const SizedBox(width: 1),
                    card(0, false),
                  ],
                ],
              )),
          if (widget.match.live ?? false)
            Padding(
              padding: const EdgeInsets.only(left: 8),
              child: Image.asset(
                Utils.getImgPath("live_video_icon.png"),
                width: 18,
                height: 14,
              ),
            )
          else if (widget.match.video == 1)
            Padding(
              padding: const EdgeInsets.only(left: 8),
              child: Image.asset(
                Utils.getImgPath("live_animation_icon.png"),
                width: 18,
                height: 14,
              ),
            )
        ],
      ),
    );
  }

  Widget events() {
    List<MajorEventList> home = widget.match.majorEventList
            ?.where((element) => element.isHome == 1)
            .toList() ??
        [];
    List<MajorEventList> guest = widget.match.majorEventList
            ?.where((element) => element.isHome == 0)
            .toList() ??
        [];
    return widget.match.majorEventList.noValue
        ? Container()
        : Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Stack(
                  children: [
                    Column(
                        children: home
                            .map((e) => eventItem(e, true))
                            .toList()
                            .insertEvery(Container(height: 2))),
                    Positioned(
                        top: 6,
                        bottom: 6,
                        right: 1.5,
                        child: Container(width: 1, color: Colours.greyD9))
                  ],
                ),
              ),
              Container(
                width: 57,
                alignment: Alignment.center,
                child: DefaultTextStyle(
                  style: const TextStyle(fontSize: 11, color: Colours.grey66),
                  child: Column(
                    children: [
                      if (widget.match.homeScoreHalf != null)
                        QsText(
                            '半:${widget.match.homeScoreHalf}-${widget.match.guestScoreHalf}'),
                      if (widget.match.homeCorner != null &&
                          config.zqList6 != 0)
                        QsText(
                            '角:${widget.match.homeCorner}-${widget.match.guestCorner}')
                    ],
                  ),
                ),
              ),
              Expanded(
                child: Stack(
                  children: [
                    Column(
                        children:
                            guest.map((e) => eventItem(e, false)).toList()),
                    Positioned(
                        top: 6,
                        bottom: 6,
                        left: 1.5,
                        child: Container(width: 1, color: Colours.greyD9))
                  ],
                ),
              )
            ],
          );
  }

  Widget bottom() {
    if (widget.match.majorEventList.noValue &&
        (widget.match.homeScoreHalf != null ||
            (widget.match.homeCorner != null && config.zqList6 != 0))) {
      return Container(
          height: 16,
          decoration: BoxDecoration(
              color: Colours.greyF5FAFF,
              borderRadius: BorderRadius.circular(2)),
          padding: const EdgeInsets.symmetric(horizontal: 4),
          child: Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                QsText(
                    (widget.match.homeScoreHalf == null
                            ? ''
                            : '半:${widget.match.homeScoreHalf}-${widget.match.guestScoreHalf}  ') +
                        (widget.match.homeCorner == null || config.zqList6 == 0
                            ? ''
                            : '角:${widget.match.homeCorner}-${widget.match.guestCorner}'),
                    color: Colours.grey66,
                    fontSize: 11)
              ]));
    }
    return const SizedBox(height: 15);
  }

  //0黄牌 1红牌
  Widget card(int type, bool isHome) {
    int? card;
    if (isHome) {
      card = (type == 0 ? widget.match.homeYellow : widget.match.homeRed);
    } else {
      card = (type == 0 ? widget.match.guestYellow : widget.match.guestRed);
    }
    ImageProvider image;
    if (type == 0) {
      if (isHome) {
        image = AssetImage(Utils.getImgPath('yellow_card_left.png'));
      } else {
        image = AssetImage(Utils.getImgPath('yellow_card_right.png'));
      }
    } else {
      if (isHome) {
        image = AssetImage(Utils.getImgPath('red_card_left.png'));
      } else {
        image = AssetImage(Utils.getImgPath('red_card_right.png'));
      }
    }
    return Visibility(
      visible: card != null,
      child: Container(
        alignment: Alignment.center,
        // margin: EdgeInsets.only(top: 2),
        width: 11,
        height: 14,
        margin: const EdgeInsets.only(bottom: 1),
        padding: const EdgeInsets.symmetric(horizontal: 3),
        decoration: BoxDecoration(
            image: DecorationImage(image: image, fit: BoxFit.fitWidth)),
        child: QsText(
          '$card',
          fontSize: 10,
          color: Colours.white,
        ),
      ),
    );
  }

  Widget eventItem(MajorEventList entity, bool isHome) {
    List<Widget> list = [
      Flexible(
          child: QsText(
        entity.name ?? "",
        maxLines: 1,
        textAlign: isHome ? TextAlign.end : TextAlign.start,
      )),
      Container(width: 4),
      QsText("${entity.time ?? " "}'", height: 1.3),
      Container(width: 6),
      Container(
          height: 13,
          alignment: Alignment.center,
          child:
              ZqMilestoneUtils.getIconWithEventType(entity.kind ?? 0, size: 8)),
      Container(width: 8),
      Container(
        margin: const EdgeInsets.symmetric(vertical: 9 / 2),
        decoration:
            const BoxDecoration(shape: BoxShape.circle, color: Colours.greyD9),
        width: 4,
        height: 4,
      )
    ];
    return DefaultTextStyle(
      style: const TextStyle(fontSize: 10, color: Colours.grey99),
      child: Row(
          mainAxisAlignment:
              isHome ? MainAxisAlignment.end : MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: isHome ? list : list.reversed.toList()),
    );
  }

  Widget dotLine(int num) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Column(
            children: List.generate(
                num,
                (index) => Container(
                      decoration: const BoxDecoration(
                          shape: BoxShape.circle, color: Colours.greyD9),
                      width: 4,
                      height: 4,
                    )).insertEvery(Container(height: 12))),
        Positioned(
            top: 0,
            bottom: 0,
            child: Container(width: 0.5, color: Colours.greyD9))
      ],
    );
  }

  Widget label(
      {required bool show,
      required String name,
      required Color color,
      String extra = ""}) {
    return !show
        ? Container()
        : GestureDetector(
            onTap: () {
              Utils.onEvent('bspd_djdcbs', params: {"bspd_djdcbs": 0});
              Get.toNamed(Routes.zqMatchDetail,
                  arguments: widget.match.id, parameters: {'tabName': name});
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  margin: const EdgeInsets.only(left: 2),
                  padding: const EdgeInsets.symmetric(horizontal: 2),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2),
                      border: Border.all(color: color, width: 0.5)),
                  child: QsText("$name$extra", fontSize: 10, color: color),
                ),
              ],
            ),
          );
  }
}
